package com.honglang.common.tools;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;


public class ZipUtil {
	public static int BUFFER_SIZE = 4096;
	
	
	public ZipOutputStream createZip(String zipFileName){
		
		try {
			ZipOutputStream zos =  new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFileName)));
			zos.setEncoding("gb2312");
			return  zos;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		//return new ZipOutputStream(new ByteArrayOutputStream());
		
	}
	
	public void compress(String filePath,ZipOutputStream zos){
		File file = new File(filePath);
		if(file.exists()){
	      	try {  
	            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));  
	            ZipEntry entry = new ZipEntry(new String(file.getName().getBytes(),"iso-8859-1"));  
	            zos.putNextEntry(entry);  
	            int count;  
	            byte data[] = new byte[BUFFER_SIZE];  
	            while ((count = bis.read(data, 0, BUFFER_SIZE)) != -1) {  
	            	zos.write(data, 0, count);  
	            }  
	            bis.close();
	            zos.closeEntry();
	            zos.close();
	            
	        } catch (Exception e) {  
	           throw new RuntimeException(e);  
	        }  
		 }
	}
	
	
	public void compress(List<String> filePathList ,ZipOutputStream zos){
		
		if(filePathList.size() > 0){
	      	try {
	      		for(String filePath : filePathList){
	      			File file = new File(filePath);
	      			if(file.exists()){
	      				BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));  
	      				ZipEntry entry = new ZipEntry(file.getName());
	      				zos.putNextEntry(entry);  
	      				int count;  
	      				byte data[] = new byte[BUFFER_SIZE];  
	      				while ((count = bis.read(data, 0, BUFFER_SIZE)) != -1) {  
	 	            	zos.write(data, 0, count);  
	      				}  
	      				zos.closeEntry();
	      				bis.close();
	      			}
	      		}
	      		zos.close();
	        } catch (Exception e) {  
	           throw new RuntimeException(e);  
	        }  
		 }
	}
	
	public static void main(String[] args){
		ZipUtil zipUtil = new ZipUtil();
		ZipOutputStream zos = zipUtil.createZip("E:/test.zip");
		List<String> fileList = new ArrayList<String>();
		fileList.add("E:/资料/freemarker中文手册.doc");
		fileList.add("E:/资料/ActionMapper.java");
		fileList.add("E:/aaa.txt");
		zipUtil.compress(fileList, zos);
		System.out.println("End");
		
	}
	
}
